package com.one.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.annotation.RequestPermission;
import com.one.annotation.RequestUser;
import com.one.bean.Management;
import com.one.bean.Product;
import com.one.service.RushToPurchaseService;
import com.one.util.RedisUtils;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
  * @author : zzh
  * @date : 2022/1/16
  * @return :
  * @description : 商品抢购活动控制层
 */
@RestController
@Slf4j
@Component
@RequestMapping("/Rush")
public class RushToPurchaseController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RushToPurchaseService rushToPurchase;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @author : zzh
     * @date : 2022/1/21
     * @return :
     * @description : 查看抢购活动
     */
    @GetMapping("/selectAllManagement")
    public List<Management> selectAllManagement(){
        return rushToPurchase.selectAllManagement();
    }



    /**
      * @author : zzh
      * @date : 2022/1/21
      * @return :
      * @description : 添加抢购活动
     */
    @PostMapping("/addManagement")
    public RequestReturn<Object> addManagement(@RequestBody Management management){
        log.info("------获取时间:{},{}------",management.getStarterTime(),management.getEndTime());
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LinkedHashMap<Object, Object> information = new LinkedHashMap<>();
        Date date1=management.getStarterTime();
        information.put("StartTime",df.format(management.getStarterTime()));
        information.put("EndTime",df.format(management.getEndTime()));
        information.put("FromTheTime",(management.getStarterTime().getTime()-date.getTime())/1000);
        information.put("TimeOfDuration",(management.getEndTime().getTime()-management.getStarterTime().getTime())/1000);
        information.put("BuyingGoods",rushToPurchase.selectBuyGoods());
        redisUtils.set("rushToActive",information);
         rushToPurchase.addManagement(management);


        log.info("------抢购商品上架成功------");
        log.info("获取时间:{}",management.getStarterTime());
        Date now = new Date();
        //设置活动前十分钟过期进行监听，给登记用户发送提醒
        redisUtils.set("RushTime",management.getStarterTime(),(management.getStarterTime().getTime()-now.getTime()-600000)/1000);
        //测试：10);//
//        Object rushToActive =
//        ObjectMapper objectMapper=new ObjectMapper();
//        Map<String, Object> innerMap = JSON.parseObject(objectMapper.toString()).getInnerMap();
//        innerMap.forEach((k,y)->{
//            System.out.print("k = " + k);
//            System.out.println("k = " + k);
//        });
        return RequestReturnFactory.success(redisUtils.get("rushToActive"));
    }


    /**
      * @author : zzh
      * @date : 2022/1/17
      * @return :
      * @description : 上架抢购商品
     */
    @GetMapping("/selectBuy")
    public RequestReturn<List<Product>> selectBuyingGoods(){
//        if (redisUtils.hasKey("Rush")){
//            log.info("******抢购商品已上架******");
//        }else {
//            redisUtils.set("Rush",rushToPurchase.selectBuyGoods(),7200);

        //获取活动开始时间
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(new Date());
//            calendar.set(Calendar.HOUR_OF_DAY, 9);
//            calendar.set(Calendar.MINUTE, 20);
//            calendar.set(Calendar.SECOND, 0);
//            Date zero = calendar.getTime();
//        List<Management> managements = rushToPurchase.selectAllManagement();
//
//        log.info("------抢购商品上架成功------");
//            log.info("获取时间:{}",zero);
//            Date now = new Date();
//            //设置活动前十分钟过期进行监听，给登记用户发送提醒
//            redisUtils.set("RushTime",zero,(zero.getTime()-now.getTime()-600000)/1000);
//        }
        return RequestReturnFactory.success();
    }

    //用户登记
    @GetMapping("/checkIn")
    @RequestPermission
    public  RequestReturn<String> userCheckIn(@RequestUser UserVo userVo, @RequestHeader String token){
        HashMap userVoHashMap = new HashMap<String,Object>();
        userVoHashMap.put("userid",userVo.getUserId());
        userVoHashMap.put("nickName",userVo.getNickname());
        userVoHashMap.put("phone",userVo.getPhone());
//        if (redisUtils.hasKey("allow")){
//            return RequestReturnFactory.fail("活动登记还未开始，请等待");
//        }else
         if(redisUtils.hasKey("userRegistration")){
            for (int i = 0; i < redisUtils.lGetListSize("userRegistration") ; i++) {
                JSONObject userRegistration = JSON.parseObject(redisUtils.lGetIndex("userRegistration", i).toString());
                if (userRegistration.getInteger("userid")==userVo.getUserId()){
                    log.info("------用户已登记，不可重复登记------");
                    return RequestReturnFactory.fail("用户已登记，不可重复登记");
                }
            }
            redisUtils.lSet("userRegistration",userVoHashMap);
            log.info("&&&&&&用户登记成功&&&&&&&");
        }else {
            redisUtils.lSet("userRegistration",userVoHashMap);
        }
        return RequestReturnFactory.success("用户登记成功");
    }

    /**
      * @author : zzh
      * @date : 2022/1/18
      * @return :
      * @description : 查询登记用户信息
     */
    @GetMapping("/selectUserCheckIn")
    public RequestReturn<List<Object>> selectUserCheckIn(){
        return RequestReturnFactory.success(redisUtils.lGet("userRegistration",0,-1));
    }


    /**
     * @author : zhukang
     * @date : 2022-01-03
     * @return :
     * @description : 使用RabbitMQ的直连交换机模式
     */
//    @Scheduled(cron = "0 41 8 * * ?")
//    public String testRabbitMQDirectExchange(){
//        List<Object> userRegistration = redisUtils.lGet("userRegistration", 0, -1);
//        rabbitTemplate.convertAndSend(RabbitMQConstant.RABBITMQ_DIRECT_EXCHANGE_KH91, RabbitMQConstant.RABBITMQ_DIRECT_ROUTING_KH91, userRegistration);
//        return null;
//    }

//    @GetMapping("/a")
//    public String queue(){
//        RushToPurchaseController rushToPurchaseController = new RushToPurchaseController();
//        return rushToPurchaseController.testRabbitMQDirectExchange();
//    }

}
